package com.msos.dao.reChargeDao;

import com.msos.model.ReCharge.ReCharge;
import com.msos.utils.CommonsUtils;
import com.msos.utils.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class reChargeDao {
    QueryRunner queryRunner = new QueryRunner(DBUtils.getDs());
    public ReCharge getReCharByNum(String cardNumber) throws SQLException {
        return queryRunner.query("select * from recharge where cardNumber=?",new BeanHandler<>(ReCharge.class),cardNumber);
    }

    public Integer addReCharge(String cardNumber, String password, String endDate) throws SQLException {
        String sql="INSERT into recharge(cardNumber,password,startDate,endDate,enabled) VALUES(?,?,?,?,?)";
        Connection con = DBUtils.getCon();
        Date date=new Date();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy--MM--dd:HH--mm--ss");
        String startDate=simpleDateFormat.format(date);
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setString(1,cardNumber);
        ps.setString(2,password);
        ps.setString(3,startDate);
        ps.setString(4,endDate);
        ps.setBoolean(5,true);
        Integer r1=ps.executeUpdate();
        DBUtils.close(ps);
        return r1;
    }

    public List<ReCharge> getAllCard() throws SQLException {
        return queryRunner.query("select * from recharge",new BeanListHandler<>(ReCharge.class));
    }

    public Integer recharCardsDele(String[] ridList) throws SQLException {
        Connection con = DBUtils.getCon();
        StringBuffer sql=new StringBuffer("delete from recharge where rid in(");
        for(int i=0;i<ridList.length;i++){
            if(i==ridList.length-1){
                sql.append("?)");
            }else {
                sql.append("?,");
            }
        }
        PreparedStatement ps = con.prepareStatement(sql.toString());
        for(int i=0;i<ridList.length;i++){
            ps.setString(i+1,ridList[i]);
        }
        Integer r1=ps.executeUpdate();
        System.out.println("（将customer置为不可用）修改记录条数r1==="+r1);
        DBUtils.close(ps);
        return r1>0? CommonsUtils.SUCCESS:CommonsUtils.FAIL;
    }
}
